<?php


namespace app\api\helpers\v1;


use Lcobucci\JWT\Builder;
use Lcobucci\JWT\Parser;
use Lcobucci\JWT\Signer\Hmac\Sha256;
use Lcobucci\JWT\ValidationData;
use InvalidArgumentException;

class jwt_token
{
    private $http_url = 'https://platform_api.test';
    //私钥，没有私钥不会认证通过
    private $secret = "_@platform";
    //令牌的过期时间
    private $tokenTtl = 3600 * 3600 * 17200;
    //
    private $uid_config = 'lhl_platform';

    /**
     * @param $uid
     * @User: 刘海龙
     * @Date: 2021/7/22
     * @Time: 15:51
     * @return string
     * 创建token
     */
    public function createToken($uid)
    {

        $signer = new Sha256();
        $token = (new Builder())->setIssuer($this->http_url)
            ->setAudience($this->http_url)
            ->setId($this->uid_config, true) // Configures the id (jti claim), replicating as a header item
            ->setIssuedAt(time()) // Configures the time that the token was issue (iat claim)
            ->setExpiration(time() + $this->tokenTtl)
            ->set('uid', $uid) // Configures a new claim, called "uid"
            ->sign(new Sha256(), $this->secret)
            ->getToken(); // 生成token
        return (string)$token;

    }

    /**
     * @param $token
     * @User: 刘海龙
     * @Date: 2021/9/22
     * @Time: 17:22
     * @return array|false
     * 验证令牌
     */
    public function checkTokenJWT($token)
    {
        try {
            $signer = new Sha256();
            if (!$token) {
                return ['code' => 10001, 'message' => 'token不能为空'];
            }
            $token = (new Parser())->parse((string)$token);
            $data = new ValidationData();
            ////先验证私钥
            if (!$token->verify($signer, $this->secret)) {
                return ['code' => 10002, 'message' => 'token密钥不对'];
            }
            //验证token是否有效
            if (!$token->validate($data)) {
                return ['code' => 10003, 'message' => '密钥过期'];
            }
            $uid = $token->getClaim('uid');
            return ['code' => 10000, 'uid' => $uid, 'message' => '验证通过'];
        } catch (InvalidArgumentException $e) {
            return false;
        }
    }
}
